﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Controls;
using MVVM_CAD.Algorithms;
using MVVM_CAD.Common;
using MVVM_CAD.Model;

namespace MVVM_CAD.Strategy
{
    public class PolygonToolStrategy : StrategyBase
    {
        public PolygonToolStrategy(IFigure figure)
            : base(figure)
        { }

        public override IFigure PerformMouseLeftClicDownEvent(Canvas canvas, IPoint point, IEnumerable<IFigure> figures)
        {
            ClickCount++;
            point.IsVertex = true;
            if (ClickCount <= 1)
            {
                ValidateFigureIsNew<Polygon>();
                Figure.PointsCollection.Add(point);
                return Figure;
            }
            var lineRepresentation = BressenhamLine.GetLineRepresentation(Figure.FinalPoint, point);
            DrawFigureInCanvas(canvas, lineRepresentation);
            Figure.PointsCollection.Add(point);
            ValidatePolygonClose(point);
            return Figure;
        }

        public override IFigure PerformMouseLeftClicUpEvent(Canvas canvas, IPoint point, IEnumerable<IFigure> figures)
        {
            throw new NotImplementedException();
        }

        private void ValidatePolygonClose(IPoint point)
        {
            if (ClickCount <= 2 || (!Figure.InitialPoint.EqualCoordinates(point))) return;
            ValidatePolygonConvexity();
            CloseFigureDrawing();
        }

        private void ValidatePolygonConvexity()
        {
            var vertices = Figure.PointsCollection.Where(p => p.IsVertex).ToArray();
            var polygon = (Polygon) Figure;
            polygon.IsConvex = SchornFisherPolygonConvexity.IsConvex(vertices);
            Figure = polygon;
        }

        public override IFigure PerformMouseRightClicDownEvent(Canvas canvas, IPoint point, IEnumerable<IFigure> figures)
        {
            throw new NotImplementedException();
        }

        public override IFigure PerformMouseMoveEvent(IPoint point, IEnumerable<IFigure> figures)
        {
            throw new NotImplementedException();
        }

        public override IFigure PerformMouseMoveEvent(DrawingCanvas Canvas, CustomPoint point)
        {
            throw new NotImplementedException();
        }
    }
}
